using System.Data.Services.Client;
using System.Linq;

namespace Common.Unity.Extensions.Entity
{
	public class ServicedEntityCreator : EntityContextCreatorBase<DataServiceContext>
	{
		public ServicedEntityCreator( DataServiceContext context ) : base( context )
		{}

		string ResolveEntitySet( object entity )
		{
			var target = entity.GetType();
			foreach ( var info in EntityContext.GetType().GetProperties() )
			{
				if ( typeof(IQueryable).IsAssignableFrom( info.PropertyType ) )
				{
					var queryable = (IQueryable)info.GetValue( EntityContext, null );
					if ( queryable.ElementType == target )
					{
						return info.Name;
					}
				}
			}
			return null;
		}

		protected override void OnCreated( object instance )
		{
			var entitySet = ResolveEntitySet( instance );
			if ( !string.IsNullOrEmpty( entitySet ) )
			{
				EntityContext.AddObject( entitySet, instance );
			}
		}
	}
}